import React, { Component } from 'react'
import { Cascader,  Spin, AutoComplete, Modal, Button, Input, Select, InputNumber, Upload, Form, Row, Col, Icon, Radio, notification, TreeSelect, message, DatePicker, TimePicker   } from 'antd';
import moment from 'moment';
import {proviceCityData} from './proviceData'
import {fetchData} from '../AjaxConsumer'
const FormItem = Form.Item;
const Option = Select.Option;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const MonthPicker = DatePicker.MonthPicker;
const RangePicker = DatePicker.RangePicker;


//提交失败错误提示
// const openNotificationWithIcon = (type,msg) => {
//   notification[type]({
//     message: '操作失败',
//     description: msg,
//   });
// };

export default class ModalForm extends React.Component {
	constructor(props) {
        super(props);
		    this.selectAutoCompleteRemoteUrl = {};
        this.selectUrl = {};
        this.selectUrlData = {};
        this.tempSelectRemoteData = {};
        this.state = {
            // contactObj : {},
            loading: false,
            confirmDirty: false,
            resData: null, //wmsAjax请求返回的数据
            treeSelectValue: undefined,
            // SelectAutoCompleteRemoteValue: [],
            SelectAutoCompleteRemoteData: {},
            getFormData: this.props.getFormData || []
          };
    }
  //点击‘确定’时触发的函数
 handleSearch = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
        // const rangeValue = fieldsValue['range-picker'];
        // const rangeTimeValue = fieldsValue['range-time-picker'];
        let datePickerValue = {};
        this.datePickerName.map((e,index)=>{
            datePickerValue[e]=  fieldsValue[e] ? fieldsValue[e].format('YYYY-MM-DD') : null;
        })
        let dateTimePickerValue = {};
        this.dateTimePickerName.map((e,index)=>{
            dateTimePickerValue[e]= fieldsValue[e] ? fieldsValue[e].format('YYYY-MM-DD HH:mm:ss') : null
        })
        let proviceName = 'provice'
        let cityName = 'city'
        let areaName = 'area'
        this.state.getFormData.map((e)=>{
          if(e.type == 'cascader'){
            proviceName = e.proviceName
            cityName = e.cityName
            areaName = e.areaName
          }
        })
        let proviceObj = [];
        if(fieldsValue.cascader != undefined){
          proviceObj.push({proviceName:fieldsValue.cascader[0]})
          proviceObj.push({cityName:fieldsValue.cascader[1]})
          proviceObj.push({areaName:fieldsValue.cascader[2]})
        }
        let values = {
            ...fieldsValue,
            ...datePickerValue,
            ...dateTimePickerValue,
            // 'date-time-picker': fieldsValue['date-time-picker'].format('YYYY-MM-DD HH:mm:ss'),
            // 'month-picker': fieldsValue['month-picker'].format('YYYY-MM'),
            // 'range-picker': [rangeValue[0].format('YYYY-MM-DD'), rangeValue[1].format('YYYY-MM-DD')],
            // 'range-time-picker': [
            //   rangeTimeValue[0].format('YYYY-MM-DD HH:mm:ss'),
            //   rangeTimeValue[1].format('YYYY-MM-DD HH:mm:ss'),
            // ],
            // 'time-picker': fieldsValue['time-picker'].format('HH:mm:ss'),
          };
          if(fieldsValue.cascader != undefined){
            values[proviceName] = fieldsValue.cascader[0];
            values[cityName] = fieldsValue.cascader[1];
            values[areaName] = fieldsValue.cascader[2];
            delete values.cascader;
          }
        if (!err) { //表单验证通过
            if (this.props.formUrl) { //若表单能获取父级URL
                this.setState({loading: true});
                // this.refs.tForm.onSubmit = this.state.loading ? '' : this.handleSearch();
                // console.log('-----------',this.refs.tForm);
                //发送ajax
                let formUrl = this.props.formUrl;
                //控制请求数据规则，无值的设为空
                for( let item in values){
                  if(!values[item]){
                    values[item] = ''
                  }
                }
                // console.log('Received values of form: ', values);
                const options= {
                    url: formUrl,
                    type: 'post',
                    condition:values
                };
                fetchData(this, options, (resData) => {
                    setTimeout(() => {
                        if (this.props.checkBox) {
                            this.props.checkBox(); //父级关闭alertModal事件
                        }
                        if (this.props.callbackUpdata) {
                            this.props.callbackUpdata() //TreeAndForm页面的函数
                        }
                        this.props.form.resetFields(); //初始化表单
                    }, 500); //loading缓冲
                    this.setState({loading: false})
                });
                // Actions.wmsAjax(formUrl, 'post', values, (res) => {
                //     setTimeout(() => {
                //         if (this.props.checkBox) {
                //             this.props.checkBox(); //父级关闭alertModal事件
                //         }
                //         if (this.props.callbackUpdata) {
                //             this.props.callbackUpdata() //TreeAndForm页面的函数
                //         }
                //         this.props.form.resetFields(); //初始化表单
                //     }, 500); //loading缓冲
                //     this.setState({loading: false})
                // },true,this);
            } else {
                // 表单无URL时，listbox需用
                if(this.props.pageNext){
                  this.props.pageNext(null, null, values)
                }
            }
        }
    });
  }
  //点击取消提交
  handleReset = () => {
    this.props.form.resetFields();  //初始化表单
    this.setState({SelectAutoCompleteRemoteData : {}})
    if (this.props.closeBox){
        this.props.closeBox(); //有弹出框的函数
    }
    //刷新父组件
    if(this.props.callbackUpdata){
        this.props.callbackUpdata()  //TreeAndForm页面的函数
    }
  }
  // 表单验证
  checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
        // console.log(this.state.confirmDirty);
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  }
  //数字验证
  checkIsNumber = (rule,value,callback) => {
    //匹配所有数字
     let reg = /^-?(?:[1-9][0-9]*|0)(?:.[0-9]+)?$/;
     const form = this.props.form;
      if (value && reg.test(value)) {
         callback();
      } else if (value && !reg.test(value)) {
         callback(['message']);
      } else {
        callback();
      }
  }
  //远程下拉选择框
  handleSelectAutoCompleteRemoteSearch = (tagName,value) => {
    //回调父级
    if(this.props.formSelectCallBack){
      if(value == undefined || value == ''){
        
      } else {
        this.props.formSelectCallBack(tagName,value)
      }
    }
    if (value != ''){
      const options= {
        url: this.selectAutoCompleteRemoteUrl[tagName]+value,
        condition:{},
        type: 'get', 
      };
      fetchData(this, options, (res) => {
        this.tempSelectRemoteData[tagName] = res.data;
        this.setState({ SelectAutoCompleteRemoteData:this.tempSelectRemoteData })
      });
    }
  }
  //selectRemote为空时清除childrenList中的数据
  handleSelectAutoCompleteRemoteChange = (tagName, value) => {
    //回调父级
    if(this.props.formSelectCallBack){
      if(value == undefined){
        value = '';
      }
      this.props.formSelectCallBack(tagName,value)
    }
  }
  //select的Change事件
  handleSelectChange = (tagName,value) => {
    // console.log('wocao!',tagName,value)
    if(this.props.formSelectCallBack){
      if(value == undefined){
        value = '';
      }
      this.props.formSelectCallBack(tagName,value)
    }
  } 
  handleSelectAutoCompleteChange=(tagName,value)=>{
    // console.log('----------',value)
    if(this.props.formSelectCallBack){
      if(value == undefined){
        value = '';
      }
      this.props.formSelectCallBack(tagName,value)
    }
  }
  handleCascaderChange = (value, selectedOptions) => {

  }
  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
      return e && e.fileList;
  }
  componentDidMount() {
    let getFormData = this.state.getFormData || [];
    //遍历带有url的下拉框，进行数据获取
    getFormData.map((e,index)=>{
        if(e.type == 'selectAutoComplete'){
          let tagName = e.name;
          const options= {
            url: e.url,
            condition:{},
            type: 'get', 
          };
          fetchData(this, options, (res) => {
            this.selectUrlData[tagName] = res.data;
            this.setState({ selectUrlData:this.selectUrlData })
          });
        }
    })
  }
  
  componentWillReceiveProps(newProps){
    this.setState({
      getFormData: newProps.getFormData
    })

  }
  datePickerName = []   //用来记录datapacker的name，在点击submit的时候需要在form传值的时候进行校验
  dateTimePickerName = []    //用来记录dateTimePicker的name，在点击submit的时候需要在form传值的时候进行校验
  render() {
    this.datePickerName = [];   //每次加载组件的时候清空，避免出现dataPcikerName重复的问题
    this.dateTimePickerName = []
    const { getFieldDecorator } = this.props.form;
    const formAlerSize = this.props.formAlerSize;
    let formItemLayout; //布局一行两个 （在传入small的时候也是一行一个）
    let formItemLayout2; //布局一行一个
    let colSpan;
    if (formAlerSize == 'small'){
        formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 18 },
        };
        formItemLayout2 = {
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        };
        colSpan = 24;
    } else if (formAlerSize == 'big') {
        //listBox 使用
        formItemLayout = {
            labelCol: { span: 9 },
            wrapperCol: { span: 15 },
        };
        //需要改变，否则不对称
        formItemLayout2 = {
          labelCol: { span: 9 },
          wrapperCol: { span: 15 },
        };
        colSpan = 6;

    } else {
        formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 15 },
        };
        //需要改变，否则不对称
        formItemLayout2 = {
          labelCol: { span: 4 },
          wrapperCol: { span: 18 },
        };
        colSpan = 11;
    }
    let FormItemStyle = {
        // marginBottom: '5px'
    }
    //最终渲染的表单组件集合
    const children = [];
    //表单数据获取
    // let getFormData = this.state.getFormData;    //若出bug请删除下一行，使用本行
    let getFormData = this.state.getFormData;
    getFormData.map((e,index)=>{
        if(e.type == 'input'){
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle} {...formItemLayout} label={e.showName} hasFeedback >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [
                            {
                              pattern:e.pattern, message:e.errorMessage
                            },{
                              required: e.required?true:false, message: '请填写此内容', //是否必填，
                            }, {
                              validator: this.checkConfirm,           //验证
                            },{
                              whitespace: true
                            }
                          ],
                        })(
                          <Input disabled={e.disable?true:false} style={{height:'33px'}}  placeholder="请输入" />
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'selectAutoComplete'){
            let selectChildren = [];
            let childrenList = [];
            if (this.state.selectUrlData){
              childrenList = this.state.selectUrlData[e.name] ? this.state.selectUrlData[e.name] : [];
            }
            childrenList.map((item)=>{
              selectChildren.push(<Option key={item[e.optionKey]} value={item[e.optionKey]} dataSearchVal={item[e.optionValue]}>{item[e.optionValue]}</Option>);
            })
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle} {...formItemLayout} label={e.showName} >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            required: e.required?true:false, message: '请选择此内容', //是否必填，
                          }, {
                            validator: this.checkConfirm,           //验证
                          }],
                        })(
                          <Select
                            showSearch
                            allowClear
                            onChange={this.handleSelectAutoCompleteChange.bind(this,e.name)}
                            disabled={e.disable?true:false}
                            optionFilterProp="children"
                            style={{height:'33px'}}
						              	disable={e.disable?true:false}
                            filterOption={(input, option) => option.props.dataSearchVal.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          >
                              {selectChildren}
                          </Select>
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'selectAutoCompleteRemote'){
            //需要把url先存到页面上
			      this.selectAutoCompleteRemoteUrl[e.name] = e.url;
            let selectChildren = [];
            let childrenList = this.state.SelectAutoCompleteRemoteData[e.name] ? this.state.SelectAutoCompleteRemoteData[e.name] : [];
            selectChildren = childrenList.map(d => <Option key={d.key} value={d.key} dataSearchVal={d.value}>{d.value}</Option>);
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle} {...formItemLayout} label={e.showName} >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            required: e.required?true:false, message: '请选择此内容', //是否必填，
                          }, {
                            validator: this.checkConfirm,           //验证
                          }],
                        })(
                          <Select
                            showSearch
                            allowClear
                            onSearch={this.handleSelectAutoCompleteRemoteSearch.bind(this,e.name)}
                            onChange={this.handleSelectAutoCompleteRemoteChange.bind(this,e.name)}
                            disabled={e.disable?true:false}
                            optionFilterProp="children"
                            style={{height:'33px'}}
                            filterOption={(input, option) => option.props.dataSearchVal.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          >
                              {selectChildren}
                          </Select>
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'password'){
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle}{...formItemLayout} label={e.showName} hasFeedback whitespace={true}>
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            required: e.required?true:false, message: '请填写此内容', //是否必填，
                          }, {
                            validator: this.checkConfirm,           //验证
                          }],
                        })(
                          <Input disabled={e.disable?true:false} style={{height:'33px'}} type='password' placeholder="请输入" />
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'email'){
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle}{...formItemLayout} label={e.showName} hasFeedback >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            type:'email', message: '请填写正确的email!',
                          }, {
                            required: e.required?true:false, message: '请填写此内容',          //验证
                          }],
                        })(
                          <Input
                            style={{height:'33px'}}
                            placeholder="请输入" 
                            disabled={e.disable?true:false}
                           />
                           
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'hiddenInput'){
            let formItemLayout = {
                labelCol: { span: 0 },
                wrapperCol: { span: 0 },
            }
            children.push(
                <Col  span={0} key={index}>
                      <FormItem
                        style={FormItemStyle}{...formItemLayout} >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                        })(
                          <Input disabled={e.disable?true:false} style={{display:'none'}} />
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'select'){
            let optionList = e.optionList ? e.optionList : [];
            if(optionList.length == 0){
              children.push(
                  <Col  span={colSpan} key={index}>
                        <FormItem
                          style={FormItemStyle}{...formItemLayout} label={e.showName} >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            required: e.required?true:false, message: '请选择此内容',
                          }, {
                            validator: this.checkConfirm,
                          }],
                        })(
                          <Select placeholder="请选择" onChange={this.handleSelectChange.bind(this,e.name)} disabled={e.disable?true:false} style={{height:'33px'}}>
                              {optionList.map((ee,eIndex)=>{
                                      return (
                                          <Option key={eIndex} value={ee.optionKey}>{ee.optionShow}</Option>
                                      )
                                  })
                              }
                          </Select>
                        )}
                        </FormItem>
                  </Col>
              )

            } else {
              children.push(
                  <Col  span={colSpan} key={index}>
                        <FormItem
                          style={FormItemStyle}{...formItemLayout} label={e.showName} >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            required: e.required?true:false, message: 'Please check the box!',
                          }, {
                            validator: this.checkConfirm,
                          }],
                        })(
                          <Select placeholder="请选择" onChange={this.handleSelectChange.bind(this,e.name)} disabled={e.disable?true:false} style={{height:'33px'}}>
                              {optionList.map((ee,eIndex)=>{
                                      return (
                                          <Option key={eIndex} value={ee.optionKey}>{ee.optionShow}</Option>
                                      )
                                  })
                              }
                          </Select>
                        )}
                        </FormItem>
                  </Col>
              )
            }
        } else if (e.type == 'textarea'){
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle}{...formItemLayout} label={e.showName} >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            required: e.required?true:false, message: '请填写此内容',
                          }, {
                            validator: this.checkConfirm,
                          }],
                        })(
                          <Input type='textarea' disabled={e.disable?true:false} placeholder="请输入" style={{height:'100px',resize:'none'}} />
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'radio'){
            let RadioColSpan = 24;
            children.push(
                <Col  span={RadioColSpan} key={index} >
                      <FormItem
                            style={FormItemStyle}{...formItemLayout2} label={e.showName} >
                      {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [{
                            required: e.required?true:false, message: '请选择此内容',
                          }, {
                            validator: this.checkConfirm,
                          }],
                      })(
                           <RadioGroup disabled={e.disable?true:false}>
                             {
                                 e.radioList.map((er,rIndex)=>{
                                     return (
                                         <Radio key={rIndex} value={er.radioKey}>{er.radioShow}</Radio>
                                     )
                                 })
                             }
                           </RadioGroup>
                       )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'number'){
            let RadioColSpan = 24;
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle}{...formItemLayout} label={e.showName} >
                        {getFieldDecorator(e.name,{
                          initialValue: e.initialValue,
                          rules: [ {
                            required: e.required?true:false, message:'请填写此内容',
                          }, {
                            validator: this.checkIsNumber, message:'请输入数字',
                          }],
                        })(
                          <Input disabled={e.disable?true:false}  />
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'cascader'){
            let RadioColSpan = 24;
            const options = proviceCityData;
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle}{...formItemLayout} label={e.showName} >
                        {getFieldDecorator('cascader',{
                          initialValue: e.initialValue,
                          rules: [ {
                            required: e.required?true:false, message:'请选择此内容',
                          }, {
                            validator: this.checkConfirm
                          }],
                        })(
                          <Cascader
                          style={{height:'33px'}}
                            options={options}
                            onChange={this.handleCascaderChange}
                            placeholder="请选择"
                            showSearch
                            disabled={e.disable?true:false}
                          />
                        )}
                      </FormItem>
                </Col>
            )
        } else if(e.type == 'uploadFile'){
            children.push(
              <Col  span={colSpan} key={index}>
                <FormItem
                    style={FormItemStyle}
                   {...formItemLayout}
                   label={e.showName}
                 >

                     <Upload disabled={e.disable?true:false} name="logo" action={e.uploadUrl} listType="picture">
                       <Button style={{height:'33px'}} >
                         <Icon type="upload" /> Click to upload
                       </Button>
                     </Upload>

                 </FormItem>
              </Col>
            )
        } else if(e.type == 'treeSelect'){
            children.push(
              <Col  span={colSpan} key={index}>
                <FormItem
                    style={FormItemStyle}
                   {...formItemLayout}
                   label={e.showName}
                 >
                   {getFieldDecorator(e.name,{
                     initialValue: e.initialValue,
                     rules: [{
                       required: e.required?true:false, message: '请选择此内容',
                     }, {
                       validator: this.checkConfirm,
                     }],
                   })(
                       <TreeSelect
                          showSearch
                          disabled={e.disable?true:false}
                          dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                          treeData={e.treeData}
                          placeholder="请选择"
                          treeDefaultExpandAll
                        />
                   )}
                 </FormItem>
              </Col>
            )
        } else if(e.type == 'dataPicker'){
            this.datePickerName.push(e.name)
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle}
                         {...formItemLayout}
                         label={e.showName}
                       >
                         {getFieldDecorator(e.name, {
                             initialValue:  e.initialValue ?  moment(e.initialValue, 'YYYY-MM-DD') : null,
                             rules: [{ type: 'object', required:  e.required?true:false, message: '请选择此内容' }],
                         })(
                           <DatePicker disabled={e.disable?true:false} style={{height:'33px'}} format='YYYY-MM-DD' />
                         )}
                       </FormItem>
                </Col>
            )
        } else if(e.type == 'dataTimePicker'){
            this.dateTimePickerName.push(e.name)
            children.push(
                <Col  span={colSpan} key={index}>
                      <FormItem
                        style={FormItemStyle}
                         {...formItemLayout}
                         label={e.showName}
                       >
                         {getFieldDecorator(e.name, {
                             initialValue: e.initialValue ? moment(e.initialValue , "YYYY-MM-DD HH:mm:ss") : null,
                             rules: [{ type: 'object', required:  e.required?true:false, message: '请选择此内容' }],
                         })(
                           <DatePicker disabled={e.disable?true:false} style={{height:'33px'}} showTime format="YYYY-MM-DD HH:mm:ss" />
                         )}
                       </FormItem>
                </Col>
            )
        }
    })

    const expand = this.state.expand;
    const shownCount = expand ? children.length : 100;
    let loading = this.state.loading;
    let submitTxt = '确定';
    let temp;
    //listBox使用
    if (formAlerSize == 'big'){
        temp = <Form
                  className="modalForm"
                  onSubmit={this.handleSearch}
                >
                  <Row gutter={5}>
                    <Col span={20} style={{ textAlign: 'center',marginTop:'5px'}}>
                        {children.slice(0, shownCount)}
                    </Col>
                    <Col span={4} style={{ textAlign: 'center',marginTop:'5px' }}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Col>
                  </Row>
                </Form>
    } else {
        temp = <Form
                  ref='tForm'
                  style={{maxHeight:'600px',overflowY:'auto', overflowX:'hidden'}}
                  className="modalForm"
                  onSubmit={this.handleSearch}
                >
                  <Row gutter={5}>
                    {children.slice(0, shownCount)}
                  </Row>
                  <Row>
                    <Col span={24} style={{ textAlign: 'center',marginTop:'30px' }}>
                      <Button type="primary" htmlType="submit">{submitTxt=loading?'提交中...':'确定'}</Button>
                      <Button style={{ marginLeft: 100 }} onClick={this.handleReset}>取消</Button>
                    </Col>
                  </Row>
                </Form>
    }
    return (
        <div>
            {temp}
        </div>
    );
  }
}
